package com.array;

/***
 * @ClassName: SparseArray
 * @Description:
 * @Auther: 送一一块二向箔
 * @Date: 17:35 2022/1/25
 * @version : V1.0
 */
public class SparseArray {

    public static void main(String[] args) {
        int[][] ints = arrayNew();
        int[][] ints1 = sparseArray(ints);
        printTwo(ints1);

        int[][] ints2 = recoveryArrays(ints1);
        printTwo(ints2);


    }


    //打印原来数组
    static int[][] arrayNew() {
        int[][] ints = new int[10][10];//10*10棋盘
        ints[1][2] = 1;
        ints[2][3] = 2;

        printTwo(ints);

        return ints;
    }


    /**
     * @Param 转换为稀疏数组
     * @Description: TODO
     * @auther: TangGuoyi
     * @date: 9:27 2022/1/26
     * @return: 输出结果为：
     * 10	10	2
     * 1	2	1
     * 2	3	2
     */
    static int[][] sparseArray(int[][] ints) {
        int count = 0;

        //判断非0个数
        for (int[] anInt : ints) {
            for (int i : anInt) {
                if (i != 0) {
                    count++;
                }
            }
        }

        //创建稀疏数组 [有效个数+1 行] [3列]
        int[][] newInts = new int[count + 1][3];
        newInts[0][0] = ints.length;
        newInts[0][1] = ints[0].length;
        newInts[0][2] = count;

        //向稀疏数组里传至
        int temp = 0;
        for (int i = 0; i < ints.length; i++) {
            for (int j = 0; j < ints[i].length; j++) {
                if (ints[i][j] != 0) {
                    temp++;
                    newInts[temp][0] = i;//记录所在行数
                    newInts[temp][1] = j;//记录所在列数
                    newInts[temp][2] = ints[i][j];//记录非零值
                }
            }
        }
        return newInts;
    }

    //打印二维数组
    static void printTwo(int[][] ints) {
        System.out.println("输出结果为：");
        for (int[] anInt : ints) {
            for (int i : anInt) {
                System.out.print(i + "\t");
            }
            System.out.println("");
        }
    }


    /**
     * @Param 稀疏数组转换为原来数组
     * @Description: TODO
     * @auther: TangGuoyi
     * @date: 9:28 2022/1/26
     * @return:
     */
    static int[][] recoveryArrays(int[][] twoArray) {
        //确定恢复数组大小 行和列在稀疏数组的第0行有记录直接取得即可
        int raw = twoArray[0][0];
        int col = twoArray[0][1];
        int[][] originalArray = new int[raw][col];

        //取得关键字个数，减小填充时间
        int keywordCount = twoArray[0][2];

        //从第一行开始遍历，第0行是记录数据，只用遍历行就行，列数是固定的，只有三列
        for (int i = 1; i <= keywordCount; i++) {
                originalArray[twoArray[i][0]][twoArray[i][1]] = twoArray[i][2];
        }
        return originalArray;
    }
}
